package com.vb.ecm.web.custom.importcontent;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class SendMail {

	private static final Logger LOGGER = Logger.getLogger(SendMail.class);
	static String d_email = "ecmdmadmin@vietinbank.vn",// login name
			d_password = "",// login password
			d_host = "10.0.160.29",// SMTP host name
			d_port = "25",// SMTP port number
			m_subject = "",// Subject
			m_text = "";// Mail Body

	public static void sendMail(String user_address, String userId, String link, String subject, String text) {

		LOGGER.debug("user_address==" + user_address);
		LOGGER.debug("subject==" + subject);
		LOGGER.debug("text==" + text);

		LOGGER.debug("MAIL START");
		Properties props = new Properties();
		props.put("mail.smtp.user", d_email);
		props.put("mail.smtp.host", d_host);
		props.put("mail.smtp.port", d_port);
		props.put("mail.smtp.starttls.enable", "true");
		// props.put("mail.smtp.auth", "true");
		// props.put("mail.smtp.socketFactory.port", d_port);
		// props.put("mail.smtp.socketFactory.class",
		// "javax.net.ssl.SSLSocketFactory");
		// props.put("mail.smtp.socketFactory.fallback", "false");

		SecurityManager security = System.getSecurityManager();

		try {
			// Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getInstance(props, null);
			/*
			 * Session session = Session.getDefaultInstance(props, new
			 * Authenticator(){ protected PasswordAuthentication
			 * getPasswordAuthentication() { return new
			 * PasswordAuthentication("smtp_user", "smtp_pass"); }});
			 */
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

			MimeMessage msg = new MimeMessage(session);

			msg.setText(text);
			msg.setSubject(subject);
			msg.setFrom(new InternetAddress(d_email));
			msg.addRecipients(Message.RecipientType.TO, user_address);
			Transport.send(msg);
			LOGGER.debug("MAIL END");
		} catch (Exception mex) {
			mex.printStackTrace();
		}
	}

	private class SMTPAuthenticator extends javax.mail.Authenticator {
		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(d_email, d_password);
		}
	}
}
